<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>XPKIT Document Generator</title>
<link rel='stylesheet' type='text/css' href='xpkit_doc.css' />
</head>

<body>
<table cellpadding=20 border=0>
<tr><td>

<?php

$cwd = str_replace ('\\', '/', getcwd());
$input_dir = $_GET["input_dir"];
$output_dir = $_GET["output_dir"];

if ($input_dir == "" || $output_dir == "") {
	$input_dir = "$cwd/..";
	$output_dir = "$cwd/html";
?>

<h2>XPKIT Document Generator</h2>
<form action="<?php print $_SERVER['PHP_SELF']; ?>">
<label>Input Directory:</label>
<input type="text" name="input_dir" value='<?php print $input_dir; ?>' size=50><br><br>
<label>Output Directory:</label>
<input type="text" name="output_dir" value='<?php print $output_dir; ?>' size=50><br><br>
<input type="submit" value="Generate Documents">
</form>

<?php
}
else {
	include ("DocFormatter.php");

	if (!is_dir($output_dir) && 
	    mkdir ($output_dir, 0700, true) == false) {
		print "ERROR: Failed to create the directory - $output_dir. Cannot proceed";
	}
	else {
		copy ("$cwd/xpkit_doc.css", "$output_dir/xpkit_doc.css");
		gen_doc ($input_dir, "");
		print "Done generating documents<br>";
	}
}

function gen_doc ($dir, $subdir)
{
	$handle = opendir ($dir);
	if ($handle == false) return false;

	while (($file = readdir($handle)) != false) {
		if ($file == "CVS" || $file == "." || $file == "..") continue;
		$full = "$dir/$file";
		if (is_dir($full)) {
			if ($subdir == "") $tmp = $file;
			else $tmp = $subdir . "/" . $file;
			gen_doc ($full, $tmp);
		}
		else {
			$len = strlen($file);
			if ($len <= 4) continue;	

			if (substr($file,$len-4,4) == ".man") {
				produce_doc ($full, $subdir, $file);
			}
		}
	}

	closedir ($handle);
}

function produce_doc ($full, $subdir, $file)
{
	global $output_dir;

	$formatter = new DocFormatter();	
	$output = $formatter->format_file ($full);
	if ($output == false) return false;

	if ($subdir == "") $name = $file;
	else $name = "$subdir/$file";
	$name = str_replace ("\\", "-", $name);
	$name = str_replace ("/", "-", $name);
	$name = substr($name, 0, strlen($name) - 4);

	$final = "$output_dir/$name.html";
	
	print "Creating $final...<br>";

	$handle = fopen ($final, "wb");
	if ($handle == false) return false;

	fwrite ($handle, "<html>\n");
	fwrite ($handle, "<head>\n");
	fwrite ($handle, "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />\n");
	fwrite ($handle, "<link rel='stylesheet' type='text/css' href='xpkit_doc.css' />\n");
	fwrite ($handle, "</head>\n");
	fwrite ($handle, "<body>\n");
	fwrite ($handle, "<table border=0 cellpadding=20>\n");
	fwrite ($handle, "<tr><td>\n");
	fwrite ($handle, $output);
	fwrite ($handle, "</td></tr>\n");
	fwrite ($handle, "</body>\n");
	fwrite ($handle, "</html>\n");
	fclose ($handle);

	return true;
}

?>

</td></tr>
</table>
</body>
</html>
